<script setup>
import { watch, reactive, ref } from 'vue'
import { useCookieStore } from '@/stores/cookieStore'
import { getFloorCommentApi, toCommentPraiseOrCancelApi } from '@/apis/comment.js'
import { postOrDeleteCommentApi } from '@/apis/comment.js'
import { ElMessage } from 'element-plus'

const useCookie = useCookieStore()

const props = defineProps(['commentId', 'id', 'type'])

// 获取楼层评论
const replyComment = ref({})
watch(() => props.commentId, async () => {
  replyComment.value = {}
  const { data } = await getFloorCommentApi({
    parentCommentId: props.commentId,
    id: props.id,
    type: props.type
  })
  replyComment.value = data.data
}, { immediate: true })

// 触底加载更多回复
const loadReply = async () => {
  const replyLength = replyComment.value.comments.length - 1
  const { data } = await getFloorCommentApi({
    parentCommentId: props.commentId,
    id: props.id,
    type: props.type,
    time: replyComment.value.comments[replyLength].time
  })
  replyComment.value.comments.push(...data.data.comments)
}

/* 回复评论 */
// 被回复的用户
const toRepliedUser = reactive({
  name: '',
  id: ''
})
// 回复的内容
const replyContent = reactive({ content: '' })
// 校验
const ruleFormRef = ref(null)
const rules = reactive({
  content: [
    { required: true, message: '请输入评论内容', trigger: 'blur' },
    { min: 1, max: 30, message: '请输入 1 - 5 长度字符', trigger: 'blur' },
  ]
})
// 处理接收回复的用户
const handleReplieUser = (name, id) => {
  toRepliedUser.name = name
  toRepliedUser.id = id
}
// 发布的回复评论
const handleRelpyComment = async () => {
  const { data } = await postOrDeleteCommentApi({
    t: 2,
    type: props.type,
    id: props.id,
    content: replyContent.content,
    commentId: toRepliedUser.id || replyComment.value.ownerComment.commentId
  })
  console.log(data)
  if (data.code === 200) {
    // 更新回复
    replyComment.value.comments.unshift(data.comment)
    replyContent.content = ''
    ElMessage({
      type: 'success',
      message: '回复成功'
    })
  } else {
    ElMessage('回复失败')
  }
}

// 点赞
const paiseComment = (id, index) => {
  toCommentPraiseOrCancel({
    commentId: id,
    t: 1,
    msg: '点赞成功',
    index: index,
    isLiked: true,
    likeCount: 1
  })
}

// 取消点赞
const cancelPraiseComment = (id, index) => {
  toCommentPraiseOrCancel({
    commentId: id,
    t: 0,
    msg: '取消点赞成功',
    index: index,
    isLiked: false,
    likeCount: -1
  })
}

// 封装后的给楼层内的评论点赞
const toCommentPraiseOrCancel = async (params) => {
  if (!useCookie.cookie.cookie) return ElMessage('点赞失败，请登录。')
  const { data } = await toCommentPraiseOrCancelApi({
    songId: props.id,
    cid: params.commentId,
    t: params.t,
    type: props.type
  })
  if (data.code === 200) {
    ElMessage({
      type: 'success',
      message: params.msg,
    })
    // 更新点赞后的状态（需判断热门评论和最新评论）
    replyComment.value.comments[params.index].liked = params.isLiked
    replyComment.value.comments[params.index].likedCount += params.likeCount
  } else {
    ElMessage('点赞失败')
  }
}
</script>

<template>
  <div class="full-reply-comment" v-if="replyComment.ownerComment">
    <div class="content" v-infinite-scroll="loadReply" :infinite-scroll-immediate="false" :infinite-scroll-delay="500">
      <!-- 楼主的评论 -->
      <div class="user-reply master-reply">
        <div class="user-info">
          <div class="info">
            <img v-lazy-image="replyComment.ownerComment.user.avatarUrl + '?param=200y200'">
            <div>
              <p>{{ replyComment.ownerComment.user.nickname }}</p>
              <p>{{ replyComment.ownerComment.timeStr || '' }}</p>
            </div>
          </div>
        </div>
        <p>{{ replyComment.ownerComment.content }}</p>
      </div>
      <!-- / 楼主的评论 -->

      <!-- 楼层内的回复 -->
      <div class="all-reply-comment">
        <h3>全部回复（{{ replyComment.totalCount }}）</h3>
        <div class="user-reply all-reply-margin" v-for="(item, index) in replyComment.comments" :key="item.commentId"
          @click="handleReplieUser(item.user.nickname, item.commentId)">
          <!-- 用户信息与回复内容 -->
          <div class="user-info">
            <div class="info">
              <img v-lazy-image="item.user.avatarUrl + '?param=200y200'">
              <div>
                <p>{{ item.user.nickname }}</p>
                <p>{{ item.timeStr || '' }}</p>
              </div>
            </div>
            <!-- 点赞 -->
            <span class="liked-info" v-if="item.liked" @click="cancelPraiseComment(item.commentId, index)">
              <i class="iconfont icon-dianzan1"></i>
              {{ item.likedCount }}
            </span>
            <span class="liked-info" v-else>
              <i class="iconfont icon-dianzan" @click="paiseComment(item.commentId, index)"></i>
              {{ item.likedCount }}
            </span>
            <!-- / 点赞 -->
          </div>
          <p class="reply-content">{{ item.content }}</p>
          <!-- / 用户信息与回复内容 -->

          <!-- 楼层内被回复的评论 -->
          <div class="be-replied-box reply-content">
            <template v-for="beReplied in item.beReplied" :key="beReplied.beRepliedCommentId">
              <div v-if="beReplied.beRepliedCommentId !== item.parentCommentId">
                <span class="be-replied-user">{{ beReplied.user.nickname }}：</span>
                <span class="be-replied-content">{{ beReplied.content }}</span>
              </div>
            </template>
          </div>
          <!-- / 楼层内被回复的评论 -->
        </div>
      </div>
      <!-- / 楼层内的回复 -->
    </div>

    <!-- 输入框 -->
    <div class="form">
      <el-form :rules="rules" :model="replyContent" ref="ruleFormRef" status-icon>
        <el-form-item prop="content">
          <el-input class="reply-input" v-model="replyContent.content"
            :placeholder="'回复 ' + (toRepliedUser.name || replyComment.ownerComment.user.nickname)" />
        </el-form-item>
      </el-form>
      <el-button type="primary" @click="handleRelpyComment">
        回复
      </el-button>
    </div>
    <!-- / 输入框 -->
  </div>
</template>

<style scoped lang='scss'>
.full-reply-comment {
  .content {
    height: 520px;
    overflow: auto;

    .user-reply {
      color: #2b2b2b;

      .user-info {
        display: flex;
        justify-content: space-between;
        margin-bottom: 10px;

        .info {
          display: flex;

          img {
            height: 40px;
            width: 40px;
            background-color: #aaa;
            border-radius: 50%;
            margin-right: 10px;
          }

          p {
            line-height: 20px;

            &:last-child {
              font-size: 12px;
              color: #aaa;
            }
          }
        }

        .liked-info {
          color: #aaa;

          .icon-dianzan1 {
            color: $primaryColor;
            cursor: pointer;
          }

          .icon-dianzan {
            cursor: pointer;
          }
        }
      }

      .reply-content {
        margin-left: 50px;
      }

      .be-replied-box {
        border-left: 3px #cdcdcd solid;
        margin-top: 10px;
        padding-left: 10px;

        .be-replied-user {
          color: $primaryColor;
        }

        .be-replied-content {
          color: #898989;
        }
      }
    }

    .master-reply {
      background-color: #fff;
      padding: 20px;
    }
  }

  .all-reply-comment {
    margin-top: 20px;
    background-color: #ffffff;
    padding: 20px;

    h3 {
      margin-bottom: 20px;
      font-size: 13px;
    }
  }

  .all-reply-margin {
    margin: 30px 0px;
  }

  .form {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 80px;
    background-color: #fff;
    padding: 0px 20px;
    box-shadow: 0px 0px 6px #dcdcdc;

    .reply-input {
      width: 420px;
      height: 40px;
    }

    button {
      width: 100px;
      height: 40px;
      letter-spacing: 5px;
    }
  }
}

:deep(.el-form-item) {
  margin-bottom: 0px;
}
</style>
